﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ReportingSite.DAL;
using ReportingSite.UserControls;
using System.Text;

namespace ReportingSite
{
    public partial class MatricsResult : System.Web.UI.Page
    {
        StringBuilder exportData = new StringBuilder();
        string type = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            Label lblPageHeading = (Label)Master.FindControl("lblPageHeading");

            HeaderMenu headerMenu = (HeaderMenu)Master.FindControl("HeaderMenu");
            LinkButton lbLastMenu = (LinkButton)headerMenu.FindControl("lbLastMenu");

            /*
            Button btnSearch = (Button)Master.FindControl("btnSearch");
            TextBox txtSearch = (TextBox)Master.FindControl("txtSearch");

            btnSearch.Visible = true;
            txtSearch.Visible = true;
             */

            

            LinkButton btnExportResult = (LinkButton)Master.FindControl("btnExportResult");
            btnExportResult.Text = "Export results to TXT";
            btnExportResult.Visible = true;

            type = Request.QueryString["type"].ToString();
            string range = Request.QueryString["range"].ToString();

           

            int hours = 0;
            string objectType = "";

            switch (range)
            {
                case "24hrs":hours = 24; 
                    break; 
                case "72hrs":
                    hours = 72;
                    break;
                case "7days":
                    hours = 7 * 24;
                    break;
                case "14days":
                    hours = 14 * 24;
                    break; 
                case "30days":
                    hours = 30 * 24;
                    break; 
                default:
                   hours = 500000;
                   break;
              }
            
            
            
            Metrics metrics = null; 

            switch (type)
            {
                case "person":
                    lblPageHeading.Text = "Person Object Metrics Page";
                    exportData.AppendLine("Person Object Metrics");
                    exportData.AppendLine(); 

                    lbLastMenu.PostBackUrl = "~/MetricsCriteria.aspx?type=person";
                    metrics = SiteProvider.Person.GetPersonObjectMetricsByTimeRange(hours);
                    objectType = "Person";
                    break;
                case "group":
                    lblPageHeading.Text = "Group Object Metrics Page";
                    exportData.AppendLine("Group Object Metrics");
                    exportData.AppendLine(); 
                    lbLastMenu.PostBackUrl = "~/MetricsCriteria.aspx?type=group";
                    metrics = SiteProvider.Group.GetGroupObjectMetricsByTimeRange(hours);
                    objectType = "Group";
                    break;
                default:
                    lblPageHeading.Text = "Object Metrics Page";
                    break;

            }

            if (range != "")
            {
                lblTimeRange.Text = range;
                exportData.AppendLine("Time Range: " + range);
            }
            else
            {
                exportData.AppendLine("Time Range: All Times");
            }

            exportData.AppendLine();

            if (metrics != null)
            {
                //assign values
                lblNumberOfChanges.Text = metrics.NumberOfChanges.ToString();
                lblNumberOfCreats.Text = metrics.NumberOfCreates.ToString();
                lblUserWithMostChangeRequests.Text = metrics.UserWithMostRequests + " (" + metrics.UserWithMostRequestsCount.ToString() +  ")";
                lblObject.Text = objectType;
                lblUserWithMostNumberOfChanges.Text = metrics.UserWithMostChanges + " (" + metrics.UserWithMostChangesCount.ToString() + ")";

                exportData.AppendLine("Number of Changes: " + metrics.NumberOfChanges.ToString());
                exportData.AppendLine("Number of Creates: " + metrics.NumberOfCreates.ToString());
                exportData.AppendLine("User with most number of change requests: " + metrics.UserWithMostRequests + " (" + metrics.UserWithMostRequestsCount.ToString() +  ")");
                
                string objectName = "Object"; 

                if (type == "person") { 
                objectName = "Person"; 
                } else if (type == "group") {
                    objectName = "Group";
                }
                exportData.AppendLine(objectName + " with most number of changes: " + metrics.UserWithMostChanges + " (" + metrics.UserWithMostChangesCount.ToString() + ")");

              

            }




        }

        private void Master_ExportData(object sender, EventArgs e)
        {

            //export to txt
            //show success or failure message
            Label lblMessage = (Label)Master.FindControl("lblMessage");

            if (ExportToTxt() == true) { 
            lblMessage.Text = "Metrics data exported successfully!";
            lblMessage.ForeColor = System.Drawing.Color.Green;
            }
            else
            {
                lblMessage.Text = "There was some error while exporting. Try again.";
                lblMessage.ForeColor = System.Drawing.Color.Red;
            }

            lblMessage.Visible = true;

        }

  

        protected void Page_PreInit(object sender, EventArgs e)
        {
            Master.ExportData += new EventHandler(Master_ExportData);
        }


        private bool ExportToTxt()
        {

            try
            {

        
            //string sFileName = System.IO.Path.GetRandomFileName();
            //string sGenName = "Friendly.txt";

            //YOu could omit these lines here as you may
            //not want to save the textfile to the server
            //I have just left them here to demonstrate that you could create the text file 
            using (System.IO.StreamWriter SW = new System.IO.StreamWriter(
                   Server.MapPath("tempfile.txt")))
            {
                SW.WriteLine(exportData.ToString());
                SW.Close();
            }

            System.IO.FileStream fs = null;
            fs = System.IO.File.Open(Server.MapPath("tempfile.txt"), System.IO.FileMode.Open);
            byte[] btFile = new byte[fs.Length];
            fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
            fs.Close();
            Response.AddHeader("Content-disposition", "attachment; filename=Metrics.txt");
            Response.ContentType = "application/octet-stream";
            Response.BinaryWrite(btFile);
            Response.End();
            }
            catch (Exception e)
            {
                return false; 
            }

            return true; 
        }
    }
}